var AjaxCrud = QualityCheck.AjaxCRUD;
var serverUrl = QualityCheck.GPUD.ServiceConfig;
var map = null;
var toolbar = null;
var scale = null;
var currentPage = 1;
var pageSize = 10;
var pointMarker = {};
$(function(){
	var usercode = $("#user-name",parent.parent.document).attr("code");
	var userkey = $("#user-name",parent.parent.document).attr("key");
	var usertype = $("#user-name",parent.parent.document).attr("usertype");
	keyCheck(usercode,usertype,userkey,function(){
		initPages();
		window.onresize = function () {
			initPages();
		};
		initTime();
		pageBtns();
		initMap();
		getSosInfo(currentPage,pageSize);
	});
});
function initTime(){
	var date = new Date();
	var newDate = getFormatDate(date,"yyyy-MM-dd hh:mm");
	var startTime = getFormatDate(new Date(date.getTime()-1000*60*60*24),"yyyy-MM-dd ");
	$("#startTime").val(startTime+"00:00");
	$("#endTime").val(newDate);
}
function initMap(){
	map = new AMap.Map("map",{
		level:15,//设置地图缩放级别
	});
	map.plugin(["AMap.ToolBar","AMap.OverView","AMap.Scale"],function(){ 
		toolbar = new AMap.ToolBar();
		toolbar.autoPosition=false; //加载工具条 
		map.addControl(toolbar);  	
		scale = new AMap.Scale(); //加载比例尺
		map.addControl(scale);
	});
	map.setDefaultCursor("url(http://developer.amap.com/wp-content/uploads/2014/06/closedhand.cur),pointer");
	$(".amap-logo").hide();
	$(".amap-copyright").hide();
	$(".amap-container").css("position","absolute");
	getNowCity();
}
function getNowCity(){
	  //加载城市查询插件
    AMap.service(["AMap.CitySearch"], function() {
        //实例化城市查询类
        var citysearch = new AMap.CitySearch();
        //自动获取用户IP，返回当前城市
        citysearch.getLocalCity(function(status, result) {
            if (status === 'complete' && result.info === 'OK') {
                if (result && result.city && result.bounds) {
                    var citybounds = result.bounds;
                    //地图显示当前城市
                    map.panTo(new AMap.LngLat(citybounds.getCenter().lng,citybounds.getCenter().lat));
                }
            }
        });
    });
}
function getSosInfo(currentpage,pagesize){
	processBegin("数据加载中······");
	var userKey = $("#user-name",parent.parent.document).attr("key");
	var schoolcode = $("#user-name",parent.parent.document).attr("schoolcode");
	var rolecode = $("#user-name",parent.parent.document).attr("rolecodes");
	var starttime = strToDate($("#startTime").val()+":00");
	var endtime = strToDate($("#endTime").val()+":59");
	var flag = $(".search-model-select").attr("model");
	var data = {
			cmd:"queryIllegalleaveSchool",
			model:"attendance",
			userKey:userKey,
			data:{
				starttime:starttime,
				endtime:endtime,
				currentpage:currentpage,
				pagesize:pagesize,
				rolecode: rolecode,
				schoolcode:schoolcode,
				flag: flag,
			},
			remark:"",
	};
	map.clearInfoWindow();
	AjaxCrud.get(serverUrl.ServerLoginUrl,data,function(res){
		var content = "";
		for(var key in pointMarker){
			if(pointMarker[key]){
				pointMarker[key].setMap(null);
			}
		}
		if(res.result == 1 && res.data != undefined && res.data != ""){
			var data = res.data.data;
			var total = res.data.count;
			totalPage = Math.ceil(total/pageSize);
			$("#total-page").text(totalPage);
			$("#now-page").text(currentpage);
			if(data.length > 0){
				for(var i = 0; i < data.length; i++){
					for(var key in data[i]){
						if(data[i][key] == null || data[i][key] == undefined){
							data[i][key] = "";
						}
					}
					content += "<div class=\"data-trs-show\" data = '"+JSON.stringify(data[i])+"'>" +
									"<div class=\"pdata-name\" title='"+data[i].name+"' style='width:180px;'>"+substr(data[i].name,13)+"</div>" +
									"<div class=\"pdata-class\" style='font-size:12px;width:180px;'>"+ data[i].grade + "年级" + data[i].clazz + "班" + "</div>" +
									"<div class=\"pdata-add\" style='width:180px;'>" + getFormatDateByLong(parseInt(data[i].time),"yyyy-MM-dd hh:mm:ss") + "</div>" +
								"</div>";
//					if(i == 0){
//						var pointArr = data[i].lonLat.split(",");
//						var y = pointArr[0];
//						var x = pointArr[1];
//						var pointObj = getPointObj(data[i]);
//						var icon = new AMap.Icon({
//							size:new AMap.Size(40,40),//图标大小
//							image:pointObj.imgUrl,//大图地址
//							imageSize:new AMap.Size(40,40)
//						});
//						addMarker(x,y,icon,pointObj.showObj,"sospoint");
//						map.panTo(new AMap.LngLat(y,x));
//					}
				}
				$(".left-datas-show").empty();
				$(".left-datas-show").append(content);
				$(".data-trs-show").click(function(){
					$(".data-trs-show").removeClass("data-trs-show-selected");
					$(this).addClass("data-trs-show-selected");
					var data = JSON.parse($(this).attr("data"));
					var id = data.id;
					var flag = data.flag;
					var pointObj = getPointObj(data);
					showDialogMes(pointObj.showObj,id,flag);
//					var lonLat = data.lonLat;
//					var pointArr = lonLat.split(",");
//					var y = pointArr[0];
//					var x = pointArr[1];
//					var icon = new AMap.Icon({
//						size:new AMap.Size(40,40),//图标大小
//						image:pointObj.imgUrl,//大图地址
//						imageSize:new AMap.Size(40,40)
//					});
//					addMarker(x,y,icon,pointObj.showObj,"sospoint");
//					map.panTo(new AMap.LngLat(y,x));
				});
			}else{
				content += "<div class='no-res-show'>未查询到相关数据！</div>";
				$(".left-datas-show").empty();
				$(".left-datas-show").append(content);
			}
			processEnd("加载成功");
		}else{
			content += "<div class='no-res-show'>查询服务出错了！</div>";
			$(".left-datas-show").empty();
			$(".left-datas-show").append(content);
			processError("加载失败");
		}
	},null,null);
}
function getPointObj(data){
	var pointObj = {};
	var showObj = {};
	showObj["姓名"] = data.name;
	showObj["IMEI"] = data.imei;
	showObj["班级"] = data.grade + "年级" + data.clazz + "班";
	showObj["就读方式"] = data.studytype;
	showObj["报警时间"] = getSmpFormatDateByLong(parseInt(data.time),true);
//	if(data.address != null){
//		showObj["当前位置"] = data.address;
//	}else{
//		showObj["当前位置"] = "暂时不能定位到准确地点";
//	}
	if(data.remark == 0 && data.remark == "0"){
		showObj["报警方式"] = "正常";
	}else if(data.remark == 1 && data.remark == "1"){
		showObj["报警方式"] = "开机报警";
	}else if(data.remark == 2 && data.remark == "2"){
		showObj["报警方式"] = "低电报警";
	}else if(data.remark == 3 && data.remark == "3"){
		showObj["报警方式"] = "紧急呼叫";
	}else if(data.remark == 4 && data.remark == "4"){
		showObj["报警方式"] = "进入电子围栏";
	}else if(data.remark == 5 && data.remark == "5"){
		showObj["报警方式"] = "非法离校";
	}else if(data.remark == 6 && data.remark == "6"){
		showObj["报警方式"] = "关机报警";
	}else if(data.remark == 8 && data.remark == "8"){
		showObj["报警方式"] = "超速报警";
	}else if(data.remark == 9 && data.remark == "9"){
		showObj["报警方式"] = "GPS 进入盲区报警";
	}else if(data.remark == 10 && data.remark == "10"){
		showObj["报警方式"] = "GPS 离开盲区报警";
	}else if(data.remark == 11 && data.remark == "11"){
		showObj["报警方式"] = "非法使用报警";
	}else{
		showObj["报警方式"] = "--";
	}
	var imgUrl = "";
	if(data.status == 0 || data.status == "0"){
		imgUrl = '../../../../img/position/lixian.png';
		showObj["定位方式"] = "离线";
	}else if(data.status == 1 || data.status == "1"){
		imgUrl = '../../../../img/position/beidou.png';
		showObj["定位方式"] = "北斗定位";
	}else if(data.status == 2 || data.status == "2"){
		imgUrl = '../../../../img/position/shinei.png';
		showObj["定位方式"] = "蓝牙定位";
	}else if(data.status == 3 || data.status == "3"){
		imgUrl = '../../../../img/position/jizhan.png';
		showObj["定位方式"] = "基站定位";
	}
	pointObj["imgUrl"] = imgUrl;
	pointObj["showObj"] = showObj;
	return pointObj;
}
function pageBtns(){
	$(".sos-search-btn").click(function(){
		getSosInfo(1,pageSize);
	});
	$("#last-page").click(function(){
		if(currentPage > 1){
			currentPage --;
			getSosInfo(currentPage,pageSize);
		}else{
			return false;
		}
	});
	$("#next-page").click(function(){
		if(currentPage < totalPage){
			currentPage ++;
			getSosInfo(currentPage,pageSize);
		}else{
			return false;
		}
	});
	$(".search-model").click(function(){
		$(".search-model").removeClass("search-model-select");
		$(this).addClass("search-model-select");
		$("#sos-dialog").hide();
		currentPage = 1;
		getSosInfo(currentPage,pageSize);
	});
}
function getNowSosInfo(){
	var date = new Date();
	var earlyDate = getFormatDate(date,"yyyy-MM-dd");
	var newDate = getFormatDate(date,"yyyy-MM-dd hh:mm:ss");
	$("#startTime").val(earlyDate + " 06:00:00");
	$("#endTime").val(newDate);
	getSosInfo(1,pageSize);
}
//添加点方法并注册线点击事件
function addMarker(x,y,icon,obj,name){
	if(pointMarker[name]){
		pointMarker[name].setMap(null);
	}
	pointMarker[name] = new AMap.Marker({
		id:name,
		position:new AMap.LngLat(y,x),
		icon:icon, //marker图标
		offset:{x:-20,y:-40} //相对于基点的位置
	});
	pointMarker[name].setMap(map);
    clickLayer(pointMarker[name],function(){
    	var content = "<table>";
	    for(key in obj){
	    	if(key == "数据时间"){
	    		if(obj[key].toString().indexOf("-") < 0){
	    			obj[key] = getSmpFormatDateByLong(parseInt(obj[key])*1000,true);
	    		}
	    	}
	        content += "<tr><td style='text-align: right;font-weight:700;width:30%;'>"+key+"：</td><td>"+obj[key]+"</td></tr>";
	    }
	    content += "</table>";
	    map.clearInfoWindow();
	    var inforWindow = new AMap.InfoWindow({
			offset:new AMap.Pixel(0,-26),
			content:content
		});
	    inforWindow.open(map,pointMarker[name].getPosition());
    });
}
function clickLayer(layer,method){
	AMap.event.addListener(layer, "click", method);
}
function showDialogMes(objs,id,flag){	
	var contents = "<table class='psos-dialog-table'>" + "<div class='psos-dialog-close'>x</div>"+
						"<tr><td class='table-psos-td1'>姓名  : </td><td class='table-psos-td2'>" + objs["姓名"] + "</td></tr>" +
						"<tr><td class='table-psos-td1'>IMEI : </td><td class='table-psos-td2'>" + objs["IMEI"] + "</td></tr>" +
						"<tr><td class='table-psos-td1'>班级  : </td><td class='table-psos-td2'>" + objs["班级"] + "</td></tr>" +
						"<tr><td class='table-psos-td1'>就读方式  : </td><td class='table-psos-td2'>" + objs["就读方式"] + "</td></tr>" +
						"<tr><td class='table-psos-td1'>报警时间  : </td><td class='table-psos-td2'>" + objs["报警时间"] + "</td></tr>"+
						"<tr><td class='table-psos-td1'>报警方式  : </td><td class='table-psos-td2'>" + objs["报警方式"] + "</td></tr>" +
						"<tr><td class='table-psos-td1'>定位方式  : </td><td class='table-psos-td2'>" + objs["定位方式"] + "</td></tr>" +
					"</table><div class='fence-edit-save' id='know-flag'>处理</div>";
	$("#sos-dialog").empty();
	$("#sos-dialog").append(contents);
	$("#sos-dialog").show();
	if(flag == 1){
		$("#know-flag").hide();
	}else{
		$("#know-flag").show();
	}
	$("#know-flag").unbind("click");
	$("#know-flag").click(function(){
		updateSos(id);
		$("#sos-dialog").hide();
	});
	$(".psos-dialog-close").unbind("click");
	$(".psos-dialog-close").click(function(){
		$("#sos-dialog").hide();
		$(".data-trs-show").removeClass("data-trs-show-selected");
	});
}
function updateSos(id){
	var userKey = $("#user-name",parent.parent.document).attr("key");
	var data = {
			cmd:"updateIllegalleaveSchool",
			model:"attendance",
			userKey:userKey,
			data:{
				id:id,
			},
			remark:"",
	};
	processBegin("正在运行中...");
	AjaxCrud.get(serverUrl.ServerLoginUrl,data,function(res){
		if(res.result == 1){
			processEnd("处理成功");
			closeDialog(function(){
				getSosInfo(currentPage,pageSize);
			});
		}else{
			processEnd("处理失败");
		}
	},null,null);
}
function substr(str,len){
	if(str != undefined){
		if(str.length > len){
			str = str.substring(0,len-2)+"...";
			return str;
		}else{
			return str;
		}
	}else{
		return "";
	}
}
function initPages(){
	var bodyRW = $("#aposition-body",parent.document).width() - $(".left-data-show").width();
	$("#map").width(bodyRW);
	
	var leftDH = $(".left-data-show").height() - $(".search-top-time").height() - $(".left-datas-page").height() - $(".left-search-data").height() - 25;
	$(".left-datas-show").height(leftDH);
}